package com.library.controller;

import com.library.entity.User;
import com.library.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @PostMapping("/login")
    public User login(@RequestBody User user, HttpSession session) {
        User loginUser = userService.login(user.getUsername(), user.getPassword());
        if (loginUser != null) {
            session.setAttribute("user", loginUser);
        }
        return loginUser;
    }
    
    @PostMapping("/logout")
    public boolean logout(HttpSession session) {
        session.removeAttribute("user");
        return true;
    }
    
    @PostMapping("/register")
    public boolean register(@RequestBody User user) {
        return userService.addUser(user);
    }
    
    @GetMapping
    public List<User> getAllUsers() {
        return userService.findAllUsers();
    }
    
    @PostMapping
    public boolean addUser(@RequestBody User user) {
        return userService.addUser(user);
    }
    
    @PutMapping("/{id}")
    public boolean updateUser(@PathVariable Integer id, @RequestBody User user) {
        user.setId(id);
        return userService.updateUser(user);
    }
    
    @DeleteMapping("/{id}")
    public boolean deleteUser(@PathVariable Integer id) {
        return userService.deleteUser(id);
    }
} 